package com.ten.mall.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.security.KeyStore;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ten.mall.utils.PayUtil;
import com.ten.mall.utils.Sign;
import com.ten.mall.vo.weixin.RefusePay;

public class WeChatConfig {
	private static Logger log = LoggerFactory.getLogger(WeChatConfig.class);
	/**
     * @Author: 刘军
     * @Description:微信退款
     * @param out_trade_no
     * @param total_fee
     * @Date: 2017-9-11 14:35
     * @return:
     */
    public static String  wxPayRefund(RefusePay refuse) {
        String data = null;
        try {
            String nonceStr = PayUtil.getRandomString(20);
            SortedMap<Object,Object> parameters = new TreeMap<>();
            parameters.put("appid", refuse.getAppid());
            parameters.put("mch_id", refuse.getMch_id());
            parameters.put("nonce_str",nonceStr);
            parameters.put("out_trade_no", refuse.getOut_trade_no());
            //parameters.put("transaction_id", transaction_id);
            parameters.put("out_refund_no", refuse.getOut_refund_no());
            parameters.put("fee_type", "CNY");
            parameters.put("total_fee", refuse.getTotal_fee());
            parameters.put("refund_fee", refuse.getRefund_fee());
            parameters.put("op_user_id",refuse.getMch_id());
            String sign = Sign.creatSign(parameters, refuse.getKey());
            log.info("退款:"+sign);
            parameters.put("sign",sign);
            data =PayUtil.SortedMaptoXml(parameters);
            log.info("data:"+data);
            } catch (Exception e) {
            System.err.println(e.getMessage());
        }
      return data;
    }
    /**
     * 证书使用
     * 微信退款
     */
    public  static String wxPayBack(String data,String mchId,File file) throws Exception {
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(file);
        // FileInputStream instream = new FileInputStream(new File("F:\\project\\myTest\\src\\main\\resources\\cert\\apiclient_cert.p12"));
        String result="";
        
        try {
            keyStore.load(instream,mchId.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore,mchId.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
            HttpPost httppost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
            StringEntity entitys = new StringEntity(data);
            httppost.setEntity((HttpEntity) entitys);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text="";
                    String t="";
                    while ((text=bufferedReader.readLine()) != null) {
                        t+=text;
                    }
                    byte[] temp=t.getBytes("utf-8");//这里写原编码方式
                    String newStr=new String(temp,"utf-8");//这里写转换后的编码方式
                    result=newStr;
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        return result;
    }
    
    public static void main(String[] args) {  
    	String appId = "wxd482ab4d4fbe5923";
    	String mchId="1418718602";
    	String out_trade_no="SH201801251516448372";
    	String key="bf80ae3c85d233b86d888a5805c62a10";
    	String out_refund_no ="ST201801250133166624"; 
    	String total_fee="1";//4200000055201801250544412798
    	String transaction_id="4200000055201801250544412798";
    	//String refund_fee = "1";// 退款金额 
       //查询退款  
    	/*String date =wxPayRefund(out_refund_no,out_trade_no,mchId,transaction_id,total_fee,appId,key);
          log.info("date:"+date);
          try {
			String ss =wxPayBack("https://api.mch.weixin.qq.com/secapi/pay/refund",date,mchId);
			log.info("ss:"+ss);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
    	
    	System.out.println(out_trade_no.replace("H", "D"));
    }  
}
